package File流;

import java.io.*;

/**
 * @author chihb
 * @create-time 2024/7/5 17:06
 * @description
 */
public class Test2 {
    public static void main(String[] args) throws Exception {
        File sourceDir=new File("E:\\javaSE");
        File destDir=new File("D:\\chiab");
        copyJavaFiles(sourceDir,destDir);
        System.out.println("复制完成");
    }
    private static void copyJavaFiles(File sourceDir,File destDir) throws Exception {
        File[] files=sourceDir.listFiles();
        if(files!=null){
            for(File file:files){
                if (file.isDirectory()) {
                    // 如果是目录，则递归调用
                    File newDestDir = new File(destDir, file.getName());
                    if (!newDestDir.exists()) {
                        newDestDir.mkdirs();
                    }
                    copyJavaFiles(file, newDestDir);
                }else if(file.isFile()&&file.getName().endsWith(".java")){
                    File destFile = new File(destDir, file.getName());
                    copyFile(file,destFile);
                    renameFile(destFile);
                }
            }
        }
    }

    private static void renameFile(File destFile) {
        String name=destFile.getName();
        String newName=name.replace(".java",".txt");
        destFile.renameTo(new File(destFile.getParent(),newName));
    }

    private static void copyFile(File file, File destFile) throws Exception {
        try (BufferedInputStream bis=
                     new BufferedInputStream(new FileInputStream(file));
             BufferedOutputStream bos=
                     new BufferedOutputStream(new FileOutputStream(destFile));){
            byte[] bytes = new byte[1024 * 5];
            int length;
            while ((length=bis.read(bytes))!=-1){
                bos.write(bytes,0,length);
            }
        }
    }
}
